#!/usr/bin/env python3

import os
import sys
import subprocess
import time
import re
import threading

# 添加模块路径
sys.path.append(os.path.expanduser('~/.config/dwm/statusbar/'))

try:
    import common
    packages_list = common.PACKAGES_LISTS
except ImportError as e:
    print(f"导入错误: {e}")
    sys.exit(1)

# 尝试导入包
loaded_modules = {}
for name in packages_list.keys():
    try:
        module = __import__(name)
        loaded_modules[name] = module
        print(f"成功导入模块: {name}")
    except ImportError as e:
        print(f"警告: 无法导入模块 {name}: {e}")

def ExecOtherFile():
    cmd = 'python3 ' + common.PACKAGES_PATH + str(sys.argv[1]) + '.py '
    for string in sys.argv[2:]:
        cmd = cmd + string + ' '
    result = subprocess.run(cmd, shell=True, timeout=3, stderr=subprocess.PIPE, stdout=subprocess.PIPE)

def MainRefresh():
    tmp = ""
    lines = ""

    common.threadLock.acquire()
    if not os.path.exists(common.TEMP_FILE):
        with open(common.TEMP_FILE, 'w') as f:
            f.write("")
    
    with open(common.TEMP_FILE, 'r') as f:
        lines = f.readlines()
    common.threadLock.release()

    for name in loaded_modules.keys():
        match_string = r"^\^s" + str(name)
        for line in lines:
            flag = re.match(match_string, line)
            if flag is not None:
                try:
                    # 使用安全的方式获取文本
                    line_text = line.encode('utf-8').decode('utf-8').replace('\n', '')
                    tmp += line_text
                    break
                except Exception as e:
                    print(f"处理模块 {name} 时出错: {e}")
    
    # 如果没有内容，显示默认信息
    if not tmp:
        tmp = "^sdatetime" + time.strftime("%Y-%m-%d %H:%M:%S")
    
    # 更新状态栏
    try:
        os.system("xsetroot -name '" + str(tmp) + "'")
    except Exception as e:
        print(f"更新状态栏时出错: {e}")

def Run():
    # 创建后台调度器
    try:
        from apscheduler.schedulers.background import BackgroundScheduler
        scheduler = BackgroundScheduler()
        
        for key, value in loaded_modules.items():
            if hasattr(loaded_modules[key], 'update_thread'):
                scheduler.add_job(
                    loaded_modules[key].update_thread, 
                    'interval', 
                    seconds=int(packages_list[key]), 
                    id=key
                )
                print(f"已安排任务: {key}, 间隔: {packages_list[key]}秒")
        
        scheduler.start()
        print("调度器启动成功")
    except Exception as e:
        print(f"调度器启动失败: {e}")

    # 主循环
    while True:
        try:
            MainRefresh()
            time.sleep(1)
        except KeyboardInterrupt:
            print("用户中断程序")
            break
        except Exception as e:
            print(f"主循环错误: {e}")
            time.sleep(5)  # 出错时等待更长时间

if __name__ == "__main__":
    if len(sys.argv) > 1:
        if sys.argv[1] == "cron":
            Run()
        elif sys.argv[1] == "update":
            pass
        else:
            ExecOtherFile()
    else:
        print("使用方法: statusbar.py [cron|update] 或 statusbar.py module_name [args]")
